package com.sanben.common.util;

import org.springframework.util.DigestUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author cyh
 * @description: md5 加密
 * @date: 2020-08-11
 */
public class MD5Util {
    public static String encrypt(String source) {
        return encodeMd5(source.getBytes());
    }

    /**
     * MD5 加密
     *
     * @param source
     * @return
     */
    private static String encodeMd5(byte[] source) {
        try {
            return encodeHex(MessageDigest.getInstance("MD5").digest(source));
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }

    private static String encodeHex(byte[] bytes) {
        StringBuffer buffer = new StringBuffer(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            if (((int) bytes[i] & 0xff) < 0x10)
                buffer.append("0");
            buffer.append(Long.toString((int) bytes[i] & 0xff, 16));
        }
        return buffer.toString();
    }

    /**
     * MD5 密码比较
     *
     * @param source
     * @param dbSource
     * @return
     */
    public static boolean decrypt(String source, String dbSource) {
        return DigestUtils.md5DigestAsHex(source.getBytes()).equals(dbSource);
    }
}
